﻿#include "musicplayer.h"
#include "volumebutton.h"

#include <QtWidgets>
#include <QtWinExtras>

MusicPlayer::MusicPlayer(QWidget *parent) : QWidget(parent)
{
    createWidgets();

    connect(&mediaPlayer, &QMediaPlayer::positionChanged, this, &MusicPlayer::updatePosition);
    connect(&mediaPlayer, &QMediaPlayer::durationChanged, this, &MusicPlayer::updateDuration);
    connect(&mediaPlayer, &QMediaObject::metaDataAvailableChanged, this, &MusicPlayer::updateInfo);

    connect(&mediaPlayer, QOverload<QMediaPlayer::Error>::of(&QMediaPlayer::error),
            this, &MusicPlayer::handleError);
    connect(&mediaPlayer, &QMediaPlayer::stateChanged,
            this, &MusicPlayer::updateState);

    stylize();
}

QStringList MusicPlayer::supportedMimeTypes()
{
    QStringList result = QMediaPlayer::supportedMimeTypes();
    if (result.isEmpty())
        result.append(QStringLiteral("audio/mpeg"));
    return result;
}

void MusicPlayer::openFile()
{
    QFileDialog fileDialog(this, "选择文件", "", "*.mp3;*.wav");
    //fileDialog.setDirectory(QStandardPaths::standardLocations(QStandardPaths::MusicLocation).value(0, QDir::homePath()));
    if (fileDialog.exec() == QDialog::Accepted)
        playUrl(fileDialog.selectedUrls().constFirst());
}

void MusicPlayer::playUrl(const QUrl &url)
{
    playButton->setEnabled(true);
    if (url.isLocalFile()) {
        const QString filePath = url.toLocalFile();
        setWindowFilePath(filePath);
        fileName = QFileInfo(filePath).fileName();
    } else {
        setWindowFilePath(QString());
        fileName.clear();
    }
    mediaPlayer.setMedia(url);
    mediaPlayer.play();
}

void MusicPlayer::pause(){
    mediaPlayer.pause();
}

void MusicPlayer::togglePlayback()
{
    if (mediaPlayer.mediaStatus() == QMediaPlayer::NoMedia)
        openFile();
    else if (mediaPlayer.state() == QMediaPlayer::PlayingState)
        mediaPlayer.pause();
    else
        mediaPlayer.play();
}

void MusicPlayer::seekForward()
{
    positionSlider->triggerAction(QSlider::SliderPageStepAdd);
}

void MusicPlayer::seekBackward()
{
    positionSlider->triggerAction(QSlider::SliderPageStepSub);
}

//! [1]
void MusicPlayer::stylize()
{
    if (QOperatingSystemVersion::current() < QOperatingSystemVersion::Windows8) {
        // Set styling options relevant only to Windows 7.
        if (QtWin::isCompositionEnabled()) {
            QtWin::extendFrameIntoClientArea(this, -1, -1, -1, -1);
            setAttribute(Qt::WA_TranslucentBackground, true);
            setAttribute(Qt::WA_NoSystemBackground, false);
            setStyleSheet(QStringLiteral("MusicPlayer { background: transparent; }"));
        } else {
            QtWin::resetExtendedFrame(this);
            setAttribute(Qt::WA_TranslucentBackground, false);
            setStyleSheet(QStringLiteral("MusicPlayer { background: %1; }").arg(QtWin::realColorizationColor().name()));
        }
        volumeButton->stylize();
    }
}
//! [1]

void MusicPlayer::updateState(QMediaPlayer::State state)
{
    if (state == QMediaPlayer::PlayingState) {
        playButton->setToolTip("暂停");
        playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause));
    } else {
        playButton->setToolTip("播放");
        playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
    }
}

static QString formatTime(qint64 timeMilliSeconds)
{
    qint64 seconds = timeMilliSeconds / 1000;
    const qint64 minutes = seconds / 60;
    seconds -= minutes * 60;
    return QStringLiteral("%1:%2")
        .arg(minutes, 2, 10, QLatin1Char('0'))
        .arg(seconds, 2, 10, QLatin1Char('0'));
}

void MusicPlayer::updatePosition(qint64 position)
{
    positionSlider->setValue(position);
    positionLabel->setText(formatTime(position));
}

void MusicPlayer::updateDuration(qint64 duration)
{
    positionSlider->setRange(0, duration);
    positionSlider->setEnabled(duration > 0);
    positionSlider->setPageStep(duration / 10);
    updateInfo();
}

void MusicPlayer::setPosition(int position)
{
    // avoid seeking when the slider value change is triggered from updatePosition()
    if (qAbs(mediaPlayer.position() - position) > 99)
        mediaPlayer.setPosition(position);
}

void MusicPlayer::updateInfo()
{
    QStringList info;
    if (!fileName.isEmpty())
        info.append(fileName);
    if (mediaPlayer.isMetaDataAvailable()) {
        QString author = mediaPlayer.metaData(QStringLiteral("Author")).toString();
        if (!author.isEmpty())
            info.append(author);
        QString title = mediaPlayer.metaData(QStringLiteral("Title")).toString();
        if (!title.isEmpty())
            info.append(title);
    }
    info.append(formatTime(mediaPlayer.duration()));
    infoLabel->setText(formatTime(mediaPlayer.duration()));
    this->setToolTip(info.join(tr(" - ")));
}

void MusicPlayer::handleError()
{
    playButton->setEnabled(false);
    const QString errorString = mediaPlayer.errorString();
    infoLabel->setText(errorString.isEmpty()
                       ? tr("未知错误 #%1").arg(int(mediaPlayer.error()))
                       : tr("错误: %1").arg(errorString));
}


void MusicPlayer::createWidgets()
{
    mediaPlayer.setVolume(100);

    volumeButton = new VolumeButton(this);
    volumeButton->setToolTip("设置音量");
    volumeButton->setVolume(mediaPlayer.volume());
    volumeButton->setStyleSheet("QToolButton{border: 0px; border-style: none;height: 22px; width: 22px; border-radius:0px;} QToolButton:hover{border: 1px solid #2993D1;} QToolButton::menu-indicator{image:none;}");
    connect(volumeButton, &VolumeButton::volumeChanged, &mediaPlayer, &QMediaPlayer::setVolume);
    connect(volumeButton, &VolumeButton::muteChanged, &mediaPlayer, &QMediaPlayer::setMuted);


    playButton = new QToolButton(this);
    playButton->setObjectName("btnMenu");
    playButton->setEnabled(false);
    playButton->setToolTip("播放");
    playButton->setFixedSize(22, 22);
    playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
    playButton->setCursor(QCursor(Qt::PointingHandCursor));
    playButton->setPopupMode(QToolButton::InstantPopup);
    playButton->setStyleSheet("QToolButton{background-color: rgba(255, 255, 255, 0.1); border-radius:0px;} QToolButton:hover{border: 1px solid #2993D1;}");
    connect(playButton, &QAbstractButton::clicked, this, &MusicPlayer::togglePlayback);

    QToolButton *openButton = new QToolButton(this);
    openButton->setObjectName("btnMenu");
    openButton->setText(QChar(0xe6a9));
    openButton->setToolTip("打开文件");
    openButton->setFixedSize(22, 22);
    openButton->setCursor(QCursor(Qt::PointingHandCursor));
    openButton->setPopupMode(QToolButton::InstantPopup);
    openButton->setStyleSheet("QToolButton{ background-color: rgba(255, 255, 255, 0.1); border-radius:0px;} QToolButton:hover{border: 1px solid #2993D1;}");
    connect(openButton, &QAbstractButton::clicked, this, &MusicPlayer::openFile);

    positionSlider = new QSlider(Qt::Horizontal, this);
    positionSlider->setEnabled(false);
    connect(positionSlider, &QAbstractSlider::valueChanged, this, &MusicPlayer::setPosition);

    infoLabel = new QLabel(tr("00:00"), this);
    positionLabel = new QLabel(tr("00:00"), this);
    positionLabel->setMinimumWidth(positionLabel->sizeHint().width());

    QBoxLayout *controlLayout = new QHBoxLayout;
    controlLayout->setMargin(0);
    controlLayout->addWidget(openButton);
    controlLayout->addWidget(playButton);
    controlLayout->addWidget(positionSlider);
    controlLayout->addWidget(volumeButton);
    controlLayout->addWidget(positionLabel);
    controlLayout->addWidget(new QLabel(tr("/"), this));
    controlLayout->addWidget(infoLabel);

    QBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setMargin(0);
    mainLayout->addLayout(controlLayout);
}
